package com.zhouyibike.uu.ui.activity.yihoudong;

import android.content.Intent;
import android.content.res.Resources;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.gyf.barlibrary.ImmersionBar;
import com.gyf.barlibrary.OnKeyboardListener;
import com.zhouyibike.uu.R;
import com.zhouyibike.uu.config.Config;
import com.zhouyibike.uu.entity.GetCodeResult;
import com.zhouyibike.uu.http.ApiCallback;
import com.zhouyibike.uu.ui.activity.web.TotalWebActivity;
import com.zhouyibike.uu.ui.adapter.MydanchevpAdapter;
import com.zhouyibike.uu.ui.base.BaseActivity;
import com.zhouyibike.uu.ui.view.MycansetscrollViewPager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;
import info.hoang8f.android.segmented.SegmentedGroup;

public class YihuodongActivity4 extends BaseActivity implements View.OnClickListener {
    private ImageButton mBtnBack;
    private TextView mBtnTitle, view_titlebar_line;
    public LinearLayout bglybglybgly;
    private MycansetscrollViewPager danchevp;
    private List<Fragment> mFragment = new ArrayList<Fragment>();
    public YihuodongmainFragment f1;
    public YihuodonglistFragment f2;
    private MydanchevpAdapter adapter;
    private SegmentedGroup gp;
    public double zhuanzengshouxufei = 0;
    public int cansellnum = 0;
    private LinearLayout ll_gengduo;
    private TextView tv_alltype_rengouxiexi, tv_alltype_zhuanzengxieyi, tv_alltype_zhuanzengshuoming,yiquanshuomingtv;
    private RelativeLayout martoply;
    private RadioButton rb21,rb22;
    public int curpage=0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_yihuodong4);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
//        initview();
//        settitleyanse(1);
//        initdata();
//        initlistener();
    }

    private void initlistener() {
        gp.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                if (i == R.id.button21) {
                    danchevp.setCurrentItem(0);
                    curpage=0;
                    settitleyanse(1);
                } else if (i == R.id.button22) {
                    danchevp.setCurrentItem(1);
                    curpage=1;
                    settitleyanse(0);
                }
            }
        });
        ll_gengduo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getyiquanWZMsg();
            }
        });
    }
    private void getyiquanWZMsg() {
        Map<String, String> params = new HashMap<>();
        params.put("token", preferences.getString("token", ""));
        params.put("type", "8");
        showProgressDialog();
        addSubscription(apiStores.GetInformationzcxy(params),
                new ApiCallback<GetCodeResult>() {

                    @Override
                    public void onSuccess(GetCodeResult model) {
                        if (model.getStatus() == Config.SUCCESSCODE) {
                            Intent i = new Intent(YihuodongActivity4.this, TotalWebActivity.class);
                            i.putExtra("title", "翼券使用说明");
                            i.putExtra("url", model.getData());
                            startActivity(i);
                        } else {
                            toastShow(model.getMessage());
                        }
                    }

                    @Override
                    public void onFailure(String msg) {
                        toastShow(msg);
                    }

                    @Override
                    public void onFinish() {
                        dismissProgressDialog();
                    }
                });
    }
    private void initdata() {
        f1 = new YihuodongmainFragment();
        f2 = new YihuodonglistFragment();
        mFragment.add(f1);
        mFragment.add(f2);
        adapter = new MydanchevpAdapter(getSupportFragmentManager(), mFragment);
        danchevp.setAdapter(adapter);
    }

    private void initview() {
        yiquanshuomingtv= (TextView) findViewById(R.id.yiquanshuomingtv2);
        rb21= (RadioButton) findViewById(R.id.button21);
        rb22= (RadioButton) findViewById(R.id.button22);
        ll_gengduo = (LinearLayout) findViewById(R.id.ll_gengduo);
        mBtnBack = (ImageButton) findViewById(R.id.bar_btn_back);
//        mBtnBack.setBackground(getResources().getDrawable(R.drawable.fanhui2));
        mBtnTitle = (TextView) findViewById(R.id.bar_text_title);
        mBtnTitle.setText("");
//        mBtnTitle.setTextColor(getResources().getColor(R.color.colorAccent));
        bglybglybgly = (LinearLayout) findViewById(R.id.bgly);
        view_titlebar_line = (TextView) findViewById(R.id.view_titlebar_line);
        view_titlebar_line.setVisibility(View.GONE);
        view_titlebar_line.setBackgroundColor(getResources().getColor(R.color.bg_main_white));
        danchevp = (MycansetscrollViewPager) findViewById(R.id.danchevp);
        danchevp.setScrollble(false);
        gp = (SegmentedGroup) findViewById(R.id.segmented2);
//        martoply = (RelativeLayout) findViewById(R.id.martoply);
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//            Log.e("onCreate: ", PhoneUtils.getStatusBarHeight(this) + "");
//            RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) martoply.getLayoutParams();
//            lp.setMargins(0, PhoneUtils.getStatusBarHeight(this), 0, 0);
//        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
//        if (requestCode == 321&& resultCode == 321) {//转券
//            //是否购买过20信息
//            Log.e("onActivityResult: ","111111" );
//            setResult(189);
//            if (f1!=null)
//            {
//                f1.dataf();
//            }else {
//                toastShow("数据刷新有误");
//            }
//            if (f2!=null)
//            {
//                f2.dataf();
//            }else {
//                toastShow("数据刷新有误");
//            }
//        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        EventBus.getDefault().unregister(this);
    }

    PopupWindow popupWindow;

    private void showpop(View view) {
        View popupWindowView = getLayoutInflater().inflate(R.layout.pop_xieyishuoming, null);
        popupWindow = new PopupWindow(popupWindowView, WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.WRAP_CONTENT);
        popupWindow.setFocusable(true);
        tv_alltype_rengouxiexi = popupWindowView.findViewById(R.id.tv_alltype_rengouxiexi);
        tv_alltype_zhuanzengxieyi = popupWindowView.findViewById(R.id.tv_alltype_zhuanzengxieyi);
        tv_alltype_zhuanzengshuoming = popupWindowView.findViewById(R.id.tv_alltype_zhuanzengjiaocheng);
        tv_alltype_rengouxiexi.setOnClickListener(this);
        tv_alltype_zhuanzengxieyi.setOnClickListener(this);
        tv_alltype_zhuanzengshuoming.setOnClickListener(this);
        // 设置允许在外点击消失
        popupWindow.setOutsideTouchable(true);
        // 这个是为了点击“返回Back”也能使其消失，并且并不会影响你的背景
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        DisplayMetrics metric = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metric);
        int width = metric.widthPixels;     // 屏幕宽度（像素）
        int pos = width - popupWindow.getWidth();
        popupWindow.showAsDropDown(this.findViewById(R.id.view_titlebar_line), pos, 0);
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                backgroundAlpha(1f);
            }
        });
    }

    public void backgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = bgAlpha; //0.0-1.0
        getWindow().setAttributes(lp);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
//            case R.id.tv_alltype_rengouxiexi:
//                popupWindow.dismiss();
//                getWZMsg("5", "单车认购协议");
//                break;
//            case R.id.tv_alltype_zhuanzengxieyi:
//                popupWindow.dismiss();
//                getWZMsg("10", "单车转赠协议");
//                break;
//            case R.id.tv_alltype_zhuanzengjiaocheng:
//                popupWindow.dismiss();
//                Intent intent3 = new Intent(YihuodongActivity3.this, FirstZhuanzengActivity.class);
//                intent3.putExtra("cansellnum", cansellnum);
//                intent3.putExtra("zhuanzengprice", zhuanzengshouxufei);
//                startActivityForResult(intent3, 666);
//                break;
        }
    }

    private void getWZMsg(String type, final String name) {
        Map<String, String> params = new HashMap<>();
        params.put("token", preferences.getString("token", ""));
        params.put("type", type);
        showProgressDialog();
        addSubscription(apiStores.GetInformationzcxy(params),
                new ApiCallback<GetCodeResult>() {

                    @Override
                    public void onSuccess(GetCodeResult model) {
                        if (model.getStatus() == Config.SUCCESSCODE) {
                            Intent i = new Intent(YihuodongActivity4.this, TotalWebActivity.class);
                            i.putExtra("title", name);
                            i.putExtra("url", model.getData());
                            startActivity(i);
                        } else {
                            toastShow(model.getMessage());
                        }
                    }

                    @Override
                    public void onFailure(String msg) {
                        toastShow(msg);
                    }

                    @Override
                    public void onFinish() {
                        dismissProgressDialog();
                    }
                });
    }

    public void settitleyanse(int i) {
        if (i==0)
        {
            mBtnBack.setBackground(getResources().getDrawable(R.mipmap.bar_return));
            yiquanshuomingtv.setTextColor(getResources().getColor(R.color.radio_button_selected_color));
            bglybglybgly.setBackgroundColor(getResources().getColor(R.color.bg_main_white));
           // gp.setTintColor(getResources().getColor(R.color.bg_main_white));
            gp.setTintColor(getResources().getColor(R.color.radio_button_selected_color));
            if (rb21.isChecked())
            {
                rb21.setTextColor(getResources().getColor(R.color.bg_main_white));
                rb22.setTextColor(getResources().getColor(R.color.radio_button_selected_color));
            }else{

            }
            if (rb22.isChecked())
            {
                rb22.setTextColor(getResources().getColor(R.color.bg_main_white));
                rb21.setTextColor(getResources().getColor(R.color.radio_button_selected_color));
            }else{

            }
//            rb22.setTextColor();
           // gp.setTintColor(getResources().getColor(R.color.radio_button_selected_color),getResources().getColor(R.color.radio_button_selected_color));
        }else{
            yiquanshuomingtv.setTextColor(getResources().getColor(R.color.bg_main_white));
            mBtnBack.setBackground(getResources().getDrawable(R.drawable.fanhui2));
            try {
                if (f1!=null&&f1.scy>5)
                {
                    bglybglybgly.setBackgroundColor(getResources().getColor(R.color.radio_button_selected_color));
                }else{
                    bglybglybgly.setBackgroundColor(getResources().getColor(R.color.transparent));
                }
            } catch (Resources.NotFoundException e) {
                e.printStackTrace();
            }
            //   gp.setTintColor(R.color.bg_main_white,R.color.radio_button_selected_color);
            gp.setTintColor(getResources().getColor(R.color.bg_main_white));
            if (rb22.isChecked())
            {
                rb21.setTextColor(getResources().getColor(R.color.bg_main_white));
                rb22.setTextColor(getResources().getColor(R.color.radio_button_selected_color));
            }else{

            }
            if (rb21.isChecked())
            {
                rb22.setTextColor(getResources().getColor(R.color.bg_main_white));
                rb21.setTextColor(getResources().getColor(R.color.radio_button_selected_color));
            }else{

            }
        }
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP)//5.0
        {

//            Build.VERSION_CODES.LOLLIPOP
        } else {
            if (i == 0) {
                ImmersionBar.with(this)
                        .transparentStatusBar()  //透明状态栏，不写默认透明色
                        //  .transparentNavigationBar()  //透明导航栏，不写默认黑色(设置此方法，fullScreen()方法自动为true)
                        //   .transparentBar()             //透明状态栏和导航栏，不写默认状态栏为透明色，导航栏为黑色（设置此方法，fullScreen()方法自动为true）
                        .statusBarColor(R.color.bg_main_white)     //状态栏颜色，不写默认透明色
                        //  .navigationBarColor(R.color.colorPrimary) //导航栏颜色，不写默认黑色
                        //   .barColor(R.color.colorPrimary)  //同时自定义状态栏和导航栏颜色，不写默认状态栏为透明色，导航栏为黑色
                        //  .statusBarAlpha(1f)  //状态栏透明度，不写默认0.0f
//                .navigationBarAlpha(0.4f)  //导航栏透明度，不写默认0.0F
//                .barAlpha(0.3f)  //状态栏和导航栏透明度，不写默认0.0f
                        .statusBarDarkFont(true)   //状态栏字体是深色，不写默认为亮色
                        .flymeOSStatusBarFontColor(R.color.text_main_3)  //修改flyme OS状态栏字体颜色
                        .fullScreen(false)      //有导航栏的情况下，activity全屏显示，也就是activity最下面被导航栏覆盖，不写默认非全屏
                        //   .hideBar(BarHide.FLAG_HIDE_BAR)  //隐藏状态栏或导航栏或两者，不写默认不隐藏
                        .fitsSystemWindows(true)    //解决状态栏和布局重叠问题，任选其一，默认为false，当为true时一定要指定statusBarColor()，不然状态栏为透明色，还有一些重载方法
                        // .supportActionBar(true) //支持ActionBar使用
                        //  .statusBarColorTransform(R.color.orange)  //状态栏变色后的颜色
//                .navigationBarColorTransform(R.color.orange) //导航栏变色后的颜色
//                .barColorTransform(R.color.orange)  //状态栏和导航栏变色后的颜色
//                .removeSupportAllView() //移除全部view支持
                        .navigationBarEnable(true)   //是否可以修改导航栏颜色，默认为true
                        .navigationBarWithKitkatEnable(true)  //是否可以修改安卓4.4和emui3.1手机导航栏颜色，默认为true
                        .fixMarginAtBottom(true)   //已过时，当xml里使用android:fitsSystemWindows="true"属性时,解决4.4和emui3.1手机底部有时会出现多余空白的问题，默认为false，非必须
                        //  .reset()  //重置所以沉浸式参数
                        .keyboardEnable(false)  //解决软键盘与底部输入框冲突问题，默认为false，还有一个重载方法，可以指定软键盘mode
                        .keyboardMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN)  //单独指定软键盘模式
                        // .keyboardMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED)  //单独指定软键盘模式
                        .setOnKeyboardListener(new OnKeyboardListener() {    //软键盘监听回调
                            @Override
                            public void onKeyboardChange(boolean isPopup, int keyboardHeight) {
//                            LogUtils.e(isPopup);  //isPopup为true，软键盘弹出，为false，软键盘关闭
                            }
                        })
                        .init();  //必须调用方可沉浸式
            } else {
                ImmersionBar.with(this)
                        .transparentStatusBar()  //透明状态栏，不写默认透明色
                        //  .transparentNavigationBar()  //透明导航栏，不写默认黑色(设置此方法，fullScreen()方法自动为true)
                        //   .transparentBar()             //透明状态栏和导航栏，不写默认状态栏为透明色，导航栏为黑色（设置此方法，fullScreen()方法自动为true）
                        .statusBarColor(R.color.radio_button_selected_color)     //状态栏颜色，不写默认透明色
                        //  .navigationBarColor(R.color.colorPrimary) //导航栏颜色，不写默认黑色
                        //   .barColor(R.color.colorPrimary)  //同时自定义状态栏和导航栏颜色，不写默认状态栏为透明色，导航栏为黑色
                        //  .statusBarAlpha(1f)  //状态栏透明度，不写默认0.0f
//                .navigationBarAlpha(0.4f)  //导航栏透明度，不写默认0.0F
//                .barAlpha(0.3f)  //状态栏和导航栏透明度，不写默认0.0f
                        .statusBarDarkFont(false)   //状态栏字体是深色，不写默认为亮色
                        .flymeOSStatusBarFontColor(R.color.bg_main_white)  //修改flyme OS状态栏字体颜色
                        .fullScreen(false)      //有导航栏的情况下，activity全屏显示，也就是activity最下面被导航栏覆盖，不写默认非全屏
                        //   .hideBar(BarHide.FLAG_HIDE_BAR)  //隐藏状态栏或导航栏或两者，不写默认不隐藏
                        .fitsSystemWindows(true)    //解决状态栏和布局重叠问题，任选其一，默认为false，当为true时一定要指定statusBarColor()，不然状态栏为透明色，还有一些重载方法
                        // .supportActionBar(true) //支持ActionBar使用
                        //  .statusBarColorTransform(R.color.orange)  //状态栏变色后的颜色
//                .navigationBarColorTransform(R.color.orange) //导航栏变色后的颜色
//                .barColorTransform(R.color.orange)  //状态栏和导航栏变色后的颜色
//                .removeSupportAllView() //移除全部view支持
                        .navigationBarEnable(true)   //是否可以修改导航栏颜色，默认为true
                        .navigationBarWithKitkatEnable(true)  //是否可以修改安卓4.4和emui3.1手机导航栏颜色，默认为true
                        .fixMarginAtBottom(true)   //已过时，当xml里使用android:fitsSystemWindows="true"属性时,解决4.4和emui3.1手机底部有时会出现多余空白的问题，默认为false，非必须
                        //  .reset()  //重置所以沉浸式参数
                        .keyboardEnable(false)  //解决软键盘与底部输入框冲突问题，默认为false，还有一个重载方法，可以指定软键盘mode
                        .keyboardMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN)  //单独指定软键盘模式
                        // .keyboardMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED)  //单独指定软键盘模式
                        .setOnKeyboardListener(new OnKeyboardListener() {    //软键盘监听回调
                            @Override
                            public void onKeyboardChange(boolean isPopup, int keyboardHeight) {
//                            LogUtils.e(isPopup);  //isPopup为true，软键盘弹出，为false，软键盘关闭
                            }
                        })
                        .init();  //必须调用方可沉浸式
            }

        }
    }
    @Subscribe(threadMode = ThreadMode.MainThread)
    public void dataff(String str) {//刷新数据
        {
            if (str.startsWith("yiquan3buyok")||str.startsWith("yiquan3sellok"))
            {
                setResult(189);
                if (f1!=null)
                {
                    f1.dataf();
                }else {
                    toastShow("数据刷新有误");
                }
                if (f2!=null)
                {
                    f2.dataf();
                }else {
                    toastShow("数据刷新有误");
                }
            }
        }
    }
}
